package org.sction.server.ftp;

import java.io.File;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.ftpserver.ConnectionConfig;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.Md5PasswordEncryptor;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.log4j.Logger;

public class FTPServerListener implements ServletContextListener {
	private FtpServer server;
	private static final String FTP_SUPPORT = "ftpSupport";
	private static final String USER_FILE = "userFile";
	private static final String USER_ADMIN = "adminUser";
	private static final String FTP_CONFIG = "ftpConfig";
	private static final String FTP_PORT = "ftpPort";
	private boolean ftpSupport = false;
	private String adminUser;
	private String ftpConfig;
	private String userFile;
	private int ftpPort = 21;
	private static Logger log = Logger.getLogger(FTPServerListener.class);

	public void contextDestroyed(ServletContextEvent arg0) {
		if (ftpSupport && server != null && !server.isStopped())
			server.stop();
	}

	public void contextInitialized(ServletContextEvent arg0) {
		ServletContext context = arg0.getServletContext();
		try {
			ftpSupport = Boolean.valueOf(context.getInitParameter(FTP_SUPPORT))
					.booleanValue();
		} catch (Exception e) {
			log.warn(FTP_SUPPORT
					+ " value in ('true','false') 未设置或设置错误，将不启动ftp服务");
		}
		adminUser = context.getInitParameter(USER_ADMIN);
		try {
			ftpPort = Integer.parseInt(context.getInitParameter(FTP_PORT));
		} catch (Exception e) {
			log.warn("ftp端口未设置或设置错误，将使用默认端口（21）");
		}
		ftpConfig = context.getInitParameter(FTP_CONFIG);
		userFile = context.getInitParameter(USER_FILE);
		// Enumeration names = context.getInitParameterNames();
		// while (names.hasMoreElements()) {
		// String name = (String) names.nextElement();
		// String value = context.getInitParameter(name);
		// if (name.equals(FTP_SUPPORT)) {
		// try {
		// ftpSupport = Boolean.parseBoolean(value);
		// } catch (Exception e) {
		// }
		// } else if (name.equals(USER_FILE)) {
		// userFile = value;
		// } else if (name.equals(USER_ADMIN)) {
		// adminUser = value;
		// } else if (name.equals(FTP_CONFIG)) {
		// ftpConfig = value;
		// }
		// }
		if (ftpSupport) {
			FtpServerFactory serverFactory = new FtpServerFactory();
			ListenerFactory factory = new ListenerFactory();
			factory.setPort(ftpPort);
			factory.setServerAddress("0.0.0.0");
			if (userFile != null) {
				PropertiesUserManagerFactory pumf = new PropertiesUserManagerFactory();
				pumf.setAdminName(adminUser);
				File userpro = new File(context.getRealPath(context
						.getContextPath()) + File.separator + userFile);
				pumf.setFile(userpro);
				Md5PasswordEncryptor md5 = new Md5PasswordEncryptor();
				pumf.setPasswordEncryptor(md5);
				serverFactory.setUserManager(pumf.createUserManager());
			}
			// FileSystemFactory fileSystem= new FileSystemFactory();
			// serverFactory.setFileSystem(fileSystem);
			// UserManager userManager = new FtpUserManager();
			ConnectionConfig connectionConfig = new FtpConnectionConfig(
					context.getRealPath(context.getContextPath())
							+ File.separator + ftpConfig);
			serverFactory.setConnectionConfig(connectionConfig);
			serverFactory.addListener("default", factory.createListener());
			server = serverFactory.createServer();

			try {
				server.start();
				log.info("FTP服务器启动.   " + factory.getServerAddress() + ":"
						+ factory.getPort());
			} catch (FtpException e) {
				log.error("FTP服务器启动失败.   " + factory.getServerAddress() + ":"
						+ factory.getPort(), e);
			}
		}
	}

}
